package com.example.demo.utils;


import com.example.demo.model.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 将List<>数据递归成，树节点的形式
 * </p>
 *
 * @author
 * @date 2021/3/24 10:27
 */

public class TreeNodeUtils {


    private final static int ROOT = 0;
    /**
     * 树的最大chen层级
     */
    private final static int DEFAULT_MAX_LEVEL = Integer.MAX_VALUE;
    /**
     * 当前节点的默认层级
     */
    private final static int DEFAULT_CUR_NODE_LEVEL = 1;

    /**
     * 查找所有根节点
     *
     * @param allNodes
     * @return Set<TreeNode>
     */
    public static List<TreeNode> findRoots(List<TreeNode> allNodes) {
        return findRoots(allNodes, DEFAULT_MAX_LEVEL);
    }

    /**
     * 查找指定最大层级的根节点
     *
     * @param allNodes
     * @param maxLevel 最大层级
     * @return Set<TreeNode>
     */
    public static List<TreeNode> findRoots(List<TreeNode> allNodes, int maxLevel) {
        // 根节点
        List<TreeNode> root = new ArrayList<>();
        allNodes.forEach(node -> {
            if (node.getParentId() == null) {
                root.add(node);
            }
        });
        root.forEach(node -> findChildren(node, allNodes, maxLevel, 1));
        return root;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNode
     * @param treeNodes
     * @param maxLevel  最大层级
     * @param curLevel  treeNode的当前层级
     * @return TreeNode
     */
    public static TreeNode findChildren(TreeNode treeNode, List<TreeNode> treeNodes, int maxLevel, int curLevel) {
        if (maxLevel == 1 || curLevel >= maxLevel) {
            return treeNode;
        }
        for (TreeNode it : treeNodes) {
            if (treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes, maxLevel, curLevel + 1));
            }
        }
        return treeNode;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNode
     * @param treeNodes
     * @return TreeNode
     */
    public static TreeNode findChildren(TreeNode treeNode, List<TreeNode> treeNodes) {
        return findChildren(treeNode, treeNodes, DEFAULT_MAX_LEVEL, DEFAULT_CUR_NODE_LEVEL);
/*        for (TreeNode it : treeNodes) {
            if (treeNode.getId() == it.getParentId()) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;*/
    }

}
